/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.jm.jmsql.cloud.email;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.util.ByteArrayDataSource;

/**
 *
 * @author Marques
 */
public class EmailGenerator {
    
    /**
     * 
     */
    public EmailGenerator() {
        super();
    }
    
    /**
     * 
     * @param template
     * @param properties
     * @return String
     * @throws java.io.IOException 
     * @throws javax.mail.MessagingException 
     */
    public BodyPart getHtmlBodyPart(String template, Map<String, String> properties) throws IOException, MessagingException {
        String html = "";
        try (InputStream is = getClass().getClassLoader().getResourceAsStream(String.format("com/jm/jmsql/cloud/email/templates/%s.html", template))) {
            try (Scanner sc = new Scanner(is)) {
                while (sc.hasNext()) {
                    html += sc.next();
                    html += sc.nextLine();
                }
            }
        }
        
        for (Entry<String, String> property : properties.entrySet()) {
            html = html.replace(property.getKey(), property.getValue());
        }
        
        BodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(html, "text/html");
        return htmlBodyPart;
    }
    
    /**
     * 
     * @param image
     * @return 
     * @throws java.io.IOException 
     * @throws javax.mail.MessagingException 
     */
    public BodyPart getImageBodyPart(String image) throws IOException, MessagingException {
        BodyPart iconBodyPart = new MimeBodyPart();
        try (InputStream is = getClass().getClassLoader().getResourceAsStream("com/jm/jmsql/cloud/images/" + image)) {
            DataSource ds = new ByteArrayDataSource(is, "image/*");
            iconBodyPart.setDataHandler(new DataHandler(ds));
            iconBodyPart.setHeader("Content-ID", "<" + image.substring(0, image.lastIndexOf(".")) + ">");
        }
        return iconBodyPart;
    }
    
}
